package thread;
// wait()、 notify()、notifyAll()的使用
public class ThreadDemo12 {
    //等待类
    static class WaitTask implements Runnable{
        private Object locker;

        public WaitTask(Object locker) {
            this.locker = locker;
        }

        @Override
        public void run() {
            while(true){
                synchronized(locker){
                    try {
                        System.out.println(Thread.currentThread().getName() + "：wait 开始！");
                        locker.wait();
                        System.out.println(Thread.currentThread().getName() + "：wait 结束！");
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
    //唤醒类
    static class NotifyTask implements Runnable{
        private Object locker;

        public NotifyTask(Object locker) {
            this.locker = locker;
        }

        @Override
        public void run() {
            synchronized (locker){
                System.out.println(Thread.currentThread().getName() + "：notify 开始！");
                //唤醒一个
                //locker.notify();
                //全部唤醒
                locker.notifyAll();
                System.out.println(Thread.currentThread().getName() + "：notify 结束！");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Object locker = new Object();

        Thread t1 = new Thread(new WaitTask(locker), "t1");
        Thread t3 = new Thread(new WaitTask(locker), "t3");
        Thread t4 = new Thread(new WaitTask(locker), "t4");
        Thread t2 = new Thread(new NotifyTask(locker), "t2");

        t1.start();
        t3.start();
        t4.start();
        Thread.sleep(1000);
        t2.start();
    }
}
